<template>
  <div>
    <van-nav-bar
      class="app-nav-bar"
      title="定位打卡"
      left-arrow
      @click-left="$router.back()"
    />
    <div class="map" id="container" style="width: 100%;height: 60vh"></div>
    <van-form
      :show-error="false"
      :show-error-message="false"
      validate-first
      @submit="onSubmit"
      @failed="onFailed"
    >
      <van-field readonly v-model="signIn.position" label="位置" rows="2" autosize type="textarea" />
      <van-field readonly v-model="signIn.time" label="时间" />
      <div class="field-btn">
        <van-button
          type="primary"
          block
          :disabled='disabled'
        >确认打卡</van-button>
      <van-button
        type="warning"
        block
        :disabled='!disabled'
      >撤销打卡</van-button>
    </div>
    </van-form>
  </div>
</template>

<script>
import AMap from 'AMap'
import { input, getSignIn, deleteSignIn } from '@/api/signIn'
export default {
  name: '',
  components: {},
  props: {},
  data () {
    return {
      disabled: true,
      signIn: {
        name: '',
        mobile: '',
        position: '',
        time: '',
        time_stamp: null,
        status: null,
        start: null,
        lng: null,
        lat: null
        // end: null
      },
      map: null,
      marker: null,
      arriveCoor: [114.59737, 36.656333],
      arrive: '' // 位置信息
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {
    // this.initMap(this.arriveCoor)
    // this.mapCoor(this.arriveCoor)
    // this.getLocation()
    this.getStatus()
  },
  methods: {
    getStatus () {
      // console.log(this.$store.state.user)
      this.signIn.start = new Date(new Date().toLocaleDateString()).getTime()
      // console.log(this.signIn.start)

      // const end = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1
      // console.log(end)

      getSignIn({
        mobile: this.$store.state.user.mobile,
        start: this.signIn.start
        // end
      }).then(res => {
        console.log('getSignIn', res)
        if (res.data?.data[0].status === 1) {
          console.log('已完成打卡')
          this.arriveCoor = [res.data.data[0].lng, res.data.data[0].lat]
          this.initMap(this.arriveCoor)
          this.signIn.position = res.data.data[0].position
          this.signIn.time = res.data.data[0].time
        } else {
          console.log('未打卡')
          this.getLocation()
        }
      }).catch(err => {
        console.log(err)
        this.getLocation()
      })
    },
    initMap (arriveCoor) {
      this.map = new AMap.Map('container', {
        center: arriveCoor, // 初始化地图中心点
        resizeEnable: true, // 是否监控地图容器尺寸变化
        zoom: 15
      })
      this.addMarker(arriveCoor)
    },
    // 实例化点标记
    addMarker (arriveCoor) {
      this.marker = new AMap.Marker({
        icon: '', // 图片ip
        imageSize: '20px',
        position: arriveCoor,
        offset: new AMap.Pixel(-13, -30),
        // 设置点标记是否可以拖拽
        draggable: false,
        cursor: 'move',
        // 设置拖拽效果
        raiseOnDrag: true
      })
      this.marker.setMap(this.map)
    },
    // 查询坐标
    mapCoor (lnglatXY) {
      var _this = this
      AMap.service('AMap.Geocoder', () => {
        var geocoder = new AMap.Geocoder({})
        geocoder.getAddress(lnglatXY, function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            _this.arrive = result.regeocode.formattedAddress
          } else {
            _this.arrive = '暂无位置'
          }
        })
      })
    },
    // 获取当前定位
    getLocation () {
      const that = this
      this.map = new AMap.Map('container', {
        center: this.arriveCoor,
        resizeEnable: true,
        zoom: 15
      })
      this.$toast.loading({
        message: '定位中...', // 提示文本
        forbidClick: true, // 禁止背景点击
        position: top,
        duration: 0 // 展示时长ms 值为0时 toast不会消失
      })
      AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位，默认:true
          timeout: 10000, // 超过10秒后停止定位，默认：5s
          buttonPosition: 'RB', // 定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点
        })
        geolocation.getCurrentPosition(function (status, result) {
          if (status === 'complete') {
            that.onComplete(result)
          } else {
            that.onError(result)
          }
        })
      })
    },
    // 解析定位结果
    onComplete (data) {
      // console.log('定位', data)
      // this.signAddress = data.formattedAddress
      // console.log(data.position.lng, data.position.lat)
      this.arriveCoor = [data.position.lng, data.position.lat]
      this.signIn.lng = data.position.lng
      this.signIn.lat = data.position.lat
      this.initMap(this.arriveCoor)
      this.$toast.success({
        message: '定位成功',
        position: top
      })
      // this.signIn.position = data.formattedAddress
      this.signIn.position = data.addressComponent.country + data.addressComponent.province + data.addressComponent.city + data.addressComponent.district

      const yy = new Date().getFullYear()
      const mm = (new Date().getMonth() + 1) < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1
      const dd = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()
      const hh = new Date().getHours()
      const mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
      const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
      var gettime = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
      // console.log(gettime)
      this.signIn.time = gettime
      this.signIn.time_stamp = new Date().getTime()
      this.signIn.status = 1
      this.disabled = false
    },
    // 解析定位错误信息
    onError (data) {
      console.log('定位失败:' + data.message)
      this.$toast.fail({
        message: '定位失败',
        position: top
      })
    },
    onSubmit () {
      if (this.disabled) {
        this.signIn.start = new Date(new Date().toLocaleDateString()).getTime()
        getSignIn({
          mobile: this.$store.state.user.mobile,
          start: this.signIn.start
        // end
        }).then(res => {
          console.log('getSignIn', res)
          if (res.data?.data[0].status === 1) {
            console.log('今日已打卡')
            this.$toast.loading({
              message: '撤回中...', // 提示文本
              forbidClick: true, // 禁止背景点击
              position: top,
              duration: 0 // 展示时长ms 值为0时 toast不会消失
            })
            deleteSignIn({ _id: res.data.data[0]._id }).then(req => {
              this.$toast.success({
                message: '撤回成功',
                position: top
              })
              this.disabled = false
              console.log('delete', req)
              this.getLocation()
            })
          } else {
            console.log('未打卡')
            this.getLocation()
          }
        }).catch(err => {
          console.log(err)
          this.getLocation()
        })
      } else {
        this.$toast.loading({
          message: '打卡中...', // 提示文本
          forbidClick: true, // 禁止背景点击
          position: top,
          duration: 0 // 展示时长ms 值为0时 toast不会消失
        })
        const { name, mobile } = this.$store.state.user
        this.signIn.name = name
        this.signIn.mobile = mobile
        // console.log('打卡表单', this.signIn)
        // console.log(this.$store.state.user)
        input(this.signIn).then(res => {
        // console.log(res)
          this.$toast.success({
            message: '打卡成功',
            position: top
          })
          this.disabled = true
          this.getStatus()
        }).catch(err => {
          console.log(err)
          this.$toast.fail({
            message: '打卡失败',
            position: top
          })
        })
      }
    },
    onFailed () {
      console.log('表单验证失败')
    }
  }
}
</script>

<style scoped lang="scss">
// .login-btn-wrap {
//   padding: 26px 16px;
//   .login-btn {
//     background-color: #6db4fb;
//     border: none;
//     .van-button__text {
//       font-size: 15px;
//     }
//   }
// }
.field-btn {
  display: flex;
  justify-content: space-around;
}
</style>
